package sfeir.ergosum;

import sfeir.ergosum.dao.DatabaseConnection;
import sfeir.ergosum.dao.DatabaseProvider;
import sfeir.ergosum.dao.RemoteProvider;
import sfeir.ergosum.emulator.AddContactQrActivity;
import sfeir.ergosum.model.Person;
import sfeir.ergosum.tools.ThemeColor;
import sfeir.ergosum.tools.VCardParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Contacts.Intents;
import android.provider.Contacts.People;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.shaded.client.android.QRCaptureActivity;
import com.sfeir.proto.hivelayout.HiveAction;
import com.sfeir.proto.hivelayout.HiveActionCell;
import com.sfeir.proto.hivelayout.HiveMenuView;

public class AddContactActivity extends Activity {
    private static final int DIALOG_PROGRESS = 1;
    private static final int DIALOG_URL_ENTRY = 2;
    private static final int DIALOG_SPREADSHEET_ENTRY = 3;
    private static final int DIALOG_TEL_ENTRY = 4;
    private static final int DIALOG_ERGOSUM_ENTRY = 5;
    // For test only :
    private static final int REQUEST_QR_SDCARD = 0;
    private static final int REQUEST_ADD_CONTACT = 1;

    private ProgressDialog mProgressDialog;
    private Thread mThread;
    private String contactData;
    final Handler mHandler = new Handler();

    final Runnable invalidContact = new Runnable() {
        public void run() {
            Toast.makeText(AddContactActivity.this,
                    getString(R.string.contact_invalid), 3000).show();

        }
    };

    private int dialogBoxType;

    private HiveMenuView hmv;

    ThemeColor theme;
    private int colorPistil;
    private int colorPetal;

    final Runnable setupHiveMenu = new Runnable() {
        public void run() {
            hmv.setup();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        theme = new ThemeColor(AddContactActivity.this);
        colorPetal = theme.getMenuColors().get(0);
        colorPistil = theme.getMenuColors().get(1);

        hmv = new HiveMenuView(this);
        // hmv.setBackgroundColor(0x40000000);
        // hmv.setBackgroundResource(R.drawable.bg);
        BitmapDrawable wallPaper = HiveActivity.getWallDrawable();
        if (wallPaper != null)
            hmv.setBackgroundDrawable(wallPaper);

        final HiveAction action1 = new HiveAction("QR") {
            public void executeAction() {
                if (0 == ((SensorManager) getSystemService(SENSOR_SERVICE))
                        .getSensors())
                    startActivityForResult(new Intent(AddContactActivity.this,
                            AddContactQrActivity.class), REQUEST_QR_SDCARD);
                else {
                    Intent intent = new Intent(AddContactActivity.this,
                            QRCaptureActivity.class);
                    intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                    startActivityForResult(intent, REQUEST_QR_SDCARD);
                }
            };
        };

        final HiveAction action2 = new HiveAction("Create") {
            public void executeAction() {
                Intent intent = new Intent(Intents.Insert.ACTION,
                        People.CONTENT_URI);
                startActivityForResult(intent, REQUEST_ADD_CONTACT);
            };
        };

        final HiveAction action3 = new HiveAction(".TEL") {
            public void executeAction() {
                showDialog(DIALOG_TEL_ENTRY);
            };
        };

        final HiveAction action4 = new HiveAction("ERGOSUM") {
            public void executeAction() {
                showDialog(DIALOG_ERGOSUM_ENTRY);
            };
        };

        final HiveAction action5 = new HiveAction("MicroFormat") {
            public void executeAction() {
                showDialog(DIALOG_URL_ENTRY);
            };
        };

        final HiveAction action6 = new HiveAction("SMS") {
            public void executeAction() {
                startActivityForResult(new Intent(AddContactActivity.this,
                        AddContactSMSMailActivity.class), HiveActivity.REFRESH);
            };
        };

        mThread = new Thread() {

            public void run() {
                Looper.prepare();

                HiveActionCell c1 = new HiveActionCell(AddContactActivity.this,
                        action1, R.drawable.qrcode);
                c1.setShown(true);
                c1.setCellColor(colorPetal);
                c1.setEmboss(true);
                hmv.setHiveMenuCell1(c1);

                HiveActionCell c2 = new HiveActionCell(AddContactActivity.this,
                        action2, R.drawable.add_user);
                c2.setShown(true);
                c2.setCellColor(colorPetal);
                c2.setEmboss(true);
                hmv.setHiveMenuCell2(c2);

                HiveActionCell c3 = new HiveActionCell(AddContactActivity.this,
                        action3, R.drawable.dottel);
                c3.setShown(true);
                c3.setCellColor(colorPetal);
                c3.setEmboss(true);
                hmv.setHiveMenuCell3(c3);

                HiveActionCell c4 = new HiveActionCell(AddContactActivity.this,
                        action4, R.drawable.ergosum);
                c4.setShown(true);
                c4.setCellColor(colorPetal);
                c4.setEmboss(true);
                hmv.setHiveMenuCell4(c4);

                HiveActionCell c5 = new HiveActionCell(AddContactActivity.this,
                        action5, R.drawable.microformats);
                c5.setShown(true);
                c5.setCellColor(colorPetal);
                c5.setEmboss(true);
                hmv.setHiveMenuCell5(c5);

                HiveActionCell c6 = new HiveActionCell(AddContactActivity.this,
                        action6, R.drawable.sms_icon);
                c6.setShown(true);
                c6.setCellColor(colorPetal);
                c6.setEmboss(true);
                hmv.setHiveMenuCell6(c6);

                HiveAction actionCancel = new HiveAction(
                        getString(R.string.main_menu_add)) {
                    public void executeAction() {
                        finish();
                    };
                };
                HiveActionCell cs = new HiveActionCell(AddContactActivity.this,
                        actionCancel, R.drawable.add_user);
                cs.setShown(true);
                cs.setCellColor(colorPistil);
                cs.setEmboss(true);
                hmv.setHiveStatusMenuCell(cs);
                // hmv.setHiveMenuCell2(cs);

                do {

                } while (!hmv.isConstantsOk());
                mHandler.post(setupHiveMenu);
                Looper.loop();

            }
        };
        mThread.start();

        setContentView(hmv);
    }

    /**
     * Create the dialog
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_PROGRESS:
            mProgressDialog = new ProgressDialog(AddContactActivity.this);
            mProgressDialog.setTitle(R.string.add_contact_wait_url);
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setButton2(getText(R.string.dialog_cancel),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {

                            mThread.stop();
                            mProgressDialog.dismiss();
                            /* User clicked No so do some stuff */
                        }
                    });
            return mProgressDialog;
        case DIALOG_SPREADSHEET_ENTRY:
            return getDialog(DIALOG_SPREADSHEET_ENTRY);
        case DIALOG_URL_ENTRY:
            return getDialog(DIALOG_TEL_ENTRY);
        case DIALOG_TEL_ENTRY:
            return getDialog(DIALOG_TEL_ENTRY);
        case DIALOG_ERGOSUM_ENTRY:
            return getDialog(DIALOG_ERGOSUM_ENTRY);
        }
        return null;
    }

    private Dialog getDialog(int dialogType) {
        dialogBoxType = dialogType;
        // This example shows how to add a custom layout to an AlertDialog
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.input_text_dialog,
                null);
        final TextView textInstruction = (TextView) textEntryView
                .findViewById(R.id.instruction_dialog);
        final EditText urlET = (EditText) textEntryView
                .findViewById(R.id.input_dialog);

        textInstruction
                .setText((dialogBoxType == DIALOG_SPREADSHEET_ENTRY) ? R.string.spreadsheet_dialog_text
                        : R.string.url_dialog_text);

        return new AlertDialog.Builder(AddContactActivity.this)
        // .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(
                        (dialogBoxType == DIALOG_SPREADSHEET_ENTRY) ? R.string.add_contact_list_add_spreadsheet
                                : R.string.add_contact_list_add_url).setView(
                        textEntryView).setPositiveButton(R.string.dialog_ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {

                                final String text = urlET.getText().toString();
                                if (text != null && !text.equals("")) {
                                    showDialog(DIALOG_PROGRESS);
                                    /* User clicked OK so do some stuff */
                                    mThread = new Thread() {
                                        public void run() {
                                            RemoteProvider dao = new RemoteProvider(
                                                    new DatabaseConnection(
                                                            getApplicationContext()));

                                            if (dialogBoxType == DIALOG_SPREADSHEET_ENTRY) {
                                                if (dao
                                                        .addContactBySpreadsheet(
                                                                text, "") == null)

                                                    mHandler
                                                            .post(invalidContact);
                                                else
                                                    AddContactActivity.this
                                                            .setResult(RESULT_OK);
                                            } else if (dialogBoxType == DIALOG_ERGOSUM_ENTRY) {
                                                if (dao
                                                        .addContactByErgoSum(text) == null)
                                                    mHandler
                                                            .post(invalidContact);
                                                else
                                                    AddContactActivity.this
                                                            .setResult(RESULT_OK);
                                            } else if (dao
                                                    .addContactByWebsite(text) == null)
                                                mHandler.post(invalidContact);
                                            else
                                                AddContactActivity.this
                                                        .setResult(RESULT_OK);
                                            mProgressDialog.dismiss();
                                        }
                                    };
                                    mThread.start();
                                }
                            }
                        }).setNegativeButton(R.string.dialog_cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                /* User clicked cancel so do some stuff */
                            }
                        }).create();
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);
        if (DIALOG_PROGRESS != id) {
            ((EditText) dialog.findViewById(R.id.input_dialog))
                    .setText(contactData);
        }
        /*
         * } else if (DIALOG_SPREADSHEET_ENTRY == id) { ((EditText)
         * dialog.findViewById(R.id.input_dialog)) .setText(contactData); }
         */
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (REQUEST_QR_SDCARD == requestCode) {
            if (RESULT_OK == resultCode) {
                this.contactData = data.getStringExtra("SCAN_RESULT");

                if (contactData.startsWith("BEGIN:VCARD")) {
                    mThread = new Thread() {
                        public void run() {
                            DatabaseProvider dp = new DatabaseProvider(
                                    new DatabaseConnection(
                                            getApplicationContext()));
                            dp.open();
                            if (null == dp.addContact(VCardParser.parse(
                                    contactData, "")))
                                mHandler.post(invalidContact);
                            else
                                AddContactActivity.this.setResult(RESULT_OK);
                            dp.close();
                            mProgressDialog.dismiss();

                        }
                    };
                    mThread.start();
                } else {
                    // if (contactData.toLowerCase().contains("http://")
                    // || contactData.toLowerCase().contains("www.") ||
                    // contactData.matches("\\."))
                    if (contactData.matches("(\\w|-)+"))
                        showDialog(DIALOG_SPREADSHEET_ENTRY);
                    else
                        showDialog(DIALOG_URL_ENTRY);
                }

            } else {
                Toast.makeText(this, "Scan cancelled", 1000).show();
            }
        }

        if (requestCode == REQUEST_ADD_CONTACT) {
            if (RESULT_OK == resultCode && data != null) {
                addContact(data.getDataString());
            }
        }

        if (requestCode == HiveActivity.REFRESH) {
            if (RESULT_OK == resultCode) {
                setResult(RESULT_OK);
            }
        }
    }

    // Lauch with an URL (hive://) or with a vcard file
    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();

        final String action = intent.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            final Uri url = intent.getData();
            if (url != null) {
                Log.e("ErgoSum", "ErgoSum open URL : " + url.toString());
                showDialog(DIALOG_PROGRESS);
                /* User clicked OK so do some stuff */
                mThread = new Thread() {
                    public void run() {
                        String type = url.getHost();
                        RemoteProvider dao = new RemoteProvider(
                                new DatabaseConnection(getApplicationContext()));
                        if (type.contains("spreadsheets.google.com")) {
                            String key = url.getQueryParameter("key");
                            String alias = url.getFragment();
                            if (alias == null)
                                alias = "";
                            if (key != null)
                                if (dao.addContactBySpreadsheet(key, alias) == null)
                                    mHandler.post(invalidContact);
                                else
                                    AddContactActivity.this
                                            .setResult(RESULT_OK);
                        } else if (url.getScheme().equals("file")) {
                            if (dao.addContactByFile(url) == null)
                                mHandler.post(invalidContact);
                            else
                                AddContactActivity.this.setResult(RESULT_OK);
                        } else if (url.getAuthority().equals("ergosum")) {
                            if (dao.addContactByErgoSum(url
                                    .getLastPathSegment()) == null)
                                mHandler.post(invalidContact);
                            else
                                AddContactActivity.this.setResult(RESULT_OK);
                        } else {
                            String u = "http:" + url.getSchemeSpecificPart();
                            if (dao.addContactByWebsite(u) == null)
                                mHandler.post(invalidContact);
                            else
                                AddContactActivity.this.setResult(RESULT_OK);
                        }

                        mProgressDialog.dismiss();

                    }
                };
                mThread.start();
            }
        }
    }

    protected void addContact(String url) {
        DatabaseConnection dc = new DatabaseConnection(this);
        DatabaseProvider dp = new DatabaseProvider(dc);

        Person person = RemoteProvider.getUpdatedPerson(url, this
                .getContentResolver());
        if (person != null) {
            dp.open();
            dp.addContact(person, url);
            dp.close();
            Toast.makeText(this, getString(R.string.profile_update_success),
                    1000).show();
        } else
            Toast.makeText(this, getString(R.string.profile_update_failure),
                    1000).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.finish();
        return false;
    }
}
